<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="google-site-verification" content="_hgg1Y3vl6FDA0y9ycG3MRMdmBljtivpN0MGPBl9Vks">
  <meta name="baidu-site-verification" content="code-BjkBUVTz39">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangduwei.top","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":true,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"gitalk | valine","storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

<script data-ad-client="ca-pub-8087648226243491" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

  <meta name="description" content="一、概述很多时候我们都有一个疑问：一个对象在内存中占用多大的空间呢？ script123456789101112131415$ jdk8-64&#x2F;java -jar jol-cli.jar internals java.lang.Object# Running 64-bit HotSpot VM.# Using compressed oop with 3-bit shift.# Using comp">
<meta property="og:type" content="article">
<meta property="og:title" content="对象的内存布局">
<meta property="og:url" content="https://wangduwei.top/java-object-layout.html">
<meta property="og:site_name" content="嗅不到北的狗子">
<meta property="og:description" content="一、概述很多时候我们都有一个疑问：一个对象在内存中占用多大的空间呢？ script123456789101112131415$ jdk8-64&#x2F;java -jar jol-cli.jar internals java.lang.Object# Running 64-bit HotSpot VM.# Using compressed oop with 3-bit shift.# Using comp">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://wangduwei.top/images/mark-word-64bit.png">
<meta property="article:published_time" content="2021-10-03T07:59:09.000Z">
<meta property="article:modified_time" content="2021-10-05T08:03:56.098Z">
<meta property="article:author" content="wangduwei">
<meta property="article:tag" content="JVM">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://wangduwei.top/images/mark-word-64bit.png">

<link rel="canonical" href="https://wangduwei.top/java-object-layout.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>对象的内存布局 | 嗅不到北的狗子</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=G-69Z1P1CBTV"></script>
    <script>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'G-69Z1P1CBTV');
      }
    </script>


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?9f3c7bb2232e1e3fda4c019e4a4406c0";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="嗅不到北的狗子" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">嗅不到北的狗子</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>站点地图</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangduwei.top/java-object-layout.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpeg">
      <meta itemprop="name" content="wangduwei">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="嗅不到北的狗子">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          对象的内存布局
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-10-03 15:59:09" itemprop="dateCreated datePublished" datetime="2021-10-03T15:59:09+08:00">2021-10-03</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-10-05 16:03:56" itemprop="dateModified" datetime="2021-10-05T16:03:56+08:00">2021-10-05</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/JVM/" itemprop="url" rel="index"><span itemprop="name">JVM</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/java-object-layout.html#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/java-object-layout.html" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>3.3k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>3 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h4 id="一、概述"><a href="#一、概述" class="headerlink" title="一、概述"></a>一、概述</h4><p>很多时候我们都有一个疑问：一个对象在内存中占用多大的空间呢？</p>
<figure class="highlight shell"><figcaption><span>script</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">$</span><span class="bash"> jdk8-64/java -jar jol-cli.jar internals java.lang.Object</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Running 64-bit HotSpot VM.</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Using compressed oop with 3-bit <span class="built_in">shift</span>.</span></span><br><span class="line"><span class="meta">#</span><span class="bash"> Using compressed klass with 3-bit <span class="built_in">shift</span>.</span></span><br><span class="line"></span><br><span class="line">Instantiated the sample instance via default constructor.</span><br><span class="line"></span><br><span class="line">java.lang.Object object internals:</span><br><span class="line"> OFFSET  SIZE   TYPE DESCRIPTION                  VALUE</span><br><span class="line">      0     4        (object header)              05 00 00 00 # Mark word</span><br><span class="line">      4     4        (object header)              00 00 00 00 # Mark word</span><br><span class="line">      8     4        (object header)              00 10 00 00 # (not mark word)</span><br><span class="line">     12     4        (loss due to the next object alignment)</span><br><span class="line">Instance size: 16 bytes</span><br><span class="line">Space losses: 0 bytes internal + 4 bytes external = 4 bytes total</span><br></pre></td></tr></table></figure>

<p>通过OpenJDK的Java-Object-Layout我们看到<code>java.lang.Object</code>的一个实例占用16 bytes。</p>
<p>同样的<code>java.lang.Boolean</code>类型占用的字节数：</p>
<figure class="highlight shell"><figcaption><span>script</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">java.lang.Boolean object internals:</span><br><span class="line"> OFFSET  SIZE      TYPE DESCRIPTION                               VALUE</span><br><span class="line">      0    12           (object header)                           N/A</span><br><span class="line">     12     1   boolean Boolean.value                             N/A</span><br><span class="line">     13     3           (loss due to the next object alignment)</span><br><span class="line">Instance size: 16 bytes</span><br><span class="line">Space losses: 0 bytes internal + 3 bytes external = 3 bytes total</span><br></pre></td></tr></table></figure>

<figure class="highlight shell"><figcaption><span>script</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[HEADER: 12 bytes]  12 </span><br><span class="line">[value:   1 byte ]  13</span><br><span class="line">[padding: 3 bytes]  16</span><br></pre></td></tr></table></figure>

<p>其实一个对象通常由三块组成，分别是：对象头、实例数据和对齐填充。</p>
<h4 id="二、对象头（object-header）"><a href="#二、对象头（object-header）" class="headerlink" title="二、对象头（object header）"></a>二、对象头（object header）</h4><p>在前面通过JOL打印输出的关于java.lang.Object信息中，我们看到object header占用12字节，但是输出并没有包含详细的结构信息，我们可以通过<a target="_blank" rel="noopener" href="http://hg.openjdk.java.net/jdk/jdk/file/19afeaa0fdbe/src/hotspot/share/oops/oop.hpp#l52">Hotspot的源码</a>了解到对象头包含两个部分：<strong>mark word</strong>和<strong>class word</strong>。</p>
<h5 id="2-1-mark-word："><a href="#2-1-mark-word：" class="headerlink" title="2.1 mark word："></a>2.1 <a target="_blank" rel="noopener" href="http://hg.openjdk.java.net/jdk/jdk/file/19afeaa0fdbe/src/hotspot/share/oops/markWord.hpp#l33">mark word</a>：</h5><p>mark word在32位和64位机分别占32位和64位，当其中锁标志位的值不同时，它前面的bit存储不同的含义。</p>
<ul>
<li>存储对象的gc年龄信息</li>
<li>存储Hashcode</li>
<li>存储锁信息</li>
</ul>
<center>
    <img src="../images/mark-word-64bit.png" width="600"/>
</center>

<h5 id="2-2-class-word"><a href="#2-2-class-word" class="headerlink" title="2.2 class word:"></a>2.2 class word:</h5><p>代码运行的时候，对象只是一串字节，我们可以通过class-word获取一些对象的元信息，它存储指向方法区中表示对象类型的指针，比如以下使用场景：</p>
<ul>
<li>运行时类型检查</li>
<li>决定对象大小</li>
<li>计算接口调用的目标类</li>
</ul>
<h5 id="2-3-数组长度："><a href="#2-3-数组长度：" class="headerlink" title="2.3 数组长度："></a>2.3 数组长度：</h5><p>如果是数组类型，对象头会额外存储数组的长度信息。</p>
<ul>
<li>快速计算对象的大小</li>
<li>数组边界检查</li>
</ul>
<h4 id="三、实例数据和对齐填充"><a href="#三、实例数据和对齐填充" class="headerlink" title="三、实例数据和对齐填充"></a>三、实例数据和对齐填充</h4><p>实例数据即我们在代码中声明的变量等信息，它的存储受到一些规则的约束以及虚拟机参数的控制。</p>
<h5 id="3-1-没有属性的类的内存布局"><a href="#3-1-没有属性的类的内存布局" class="headerlink" title="3.1 没有属性的类的内存布局"></a>3.1 没有属性的类的内存布局</h5><blockquote>
<p>规则一：每个对象都是八字节对齐。</p>
</blockquote>
<p>从前面Object的输出中，我们看到，当一个对象只有头部信息时占用16byte，刚好是8的整数倍。</p>
<h5 id="3-2-Object子类的内存布局"><a href="#3-2-Object子类的内存布局" class="headerlink" title="3.2 Object子类的内存布局"></a>3.2 Object子类的内存布局</h5><p>跟在对象头后面的类属性按照它们的大小在内存中排序，例如：int是4字节、long是8字节。采用字节对齐可以提高性能，因为从内存读取4字节到4字节的寄存器性能更好。</p>
<p>为了节约内存，Sun的虚拟机在分配对象字段的时候和它们声明的顺序不同，有如下顺序规则：</p>
<p>1、double和long类型<br>2、int和float<br>3、short和char<br>4、boolean和byte<br>5、reference</p>
<p>为什么可以优化内存呢？我们看一下这个例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MyClass</span> </span>&#123;</span><br><span class="line">    <span class="keyword">byte</span> a;</span><br><span class="line">    <span class="keyword">int</span> c;</span><br><span class="line">    <span class="keyword">boolean</span> d;</span><br><span class="line">    <span class="keyword">long</span> e;</span><br><span class="line">    Object f;        </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>它的对象布局如下：</p>
<figure class="highlight shell"><figcaption><span>script</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">[HEADER:  8 bytes]  8</span><br><span class="line">[a:       1 byte ]  9</span><br><span class="line">[padding: 3 bytes] 12</span><br><span class="line">[c:       4 bytes] 16</span><br><span class="line">[d:       1 byte ] 17</span><br><span class="line">[padding: 7 bytes] 24</span><br><span class="line">[e:       8 bytes] 32</span><br><span class="line">[f:       4 bytes] 36</span><br><span class="line">[padding: 4 bytes] 40</span><br></pre></td></tr></table></figure>
<p>总共使用了40字节内存，其中14个用于内存对齐而浪费掉。如果重排顺序则：</p>
<figure class="highlight shell"><figcaption><span>script</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">[HEADER:  8 bytes]  8</span><br><span class="line">[e:       8 bytes] 16</span><br><span class="line">[c:       4 bytes] 20</span><br><span class="line">[a:       1 byte ] 21</span><br><span class="line">[d:       1 byte ] 22</span><br><span class="line">[padding: 2 bytes] 24</span><br><span class="line">[f:       4 bytes] 28</span><br><span class="line">[padding: 4 bytes] 32</span><br></pre></td></tr></table></figure>

<p>经过优化后只有6个字节用于对齐填充，总内存也只有32byte。</p>
<h5 id="3-3-子类的内存布局"><a href="#3-3-子类的内存布局" class="headerlink" title="3.3 子类的内存布局"></a>3.3 子类的内存布局</h5><blockquote>
<p>规则三：继承结构中属于不同类的字段不混合在一起。父类优先，子类其次。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">   <span class="keyword">long</span> a;</span><br><span class="line">   <span class="keyword">int</span> b;</span><br><span class="line">   <span class="keyword">int</span> c;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> <span class="keyword">extends</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">   <span class="keyword">long</span> d;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>B类的布局如下：</p>
<figure class="highlight shell"><figcaption><span>script</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[HEADER:  8 bytes]  8</span><br><span class="line">[a:       8 bytes] 16</span><br><span class="line">[b:       4 bytes] 20</span><br><span class="line">[c:       4 bytes] 24</span><br><span class="line">[d:       8 bytes] 32</span><br></pre></td></tr></table></figure>

<p>如果父类的字段不符合4字节对齐。</p>
<blockquote>
<p>规则四：父类的最后一个字段和子类第一个字段之间必须4字节对齐。</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">   <span class="keyword">byte</span> a;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> </span>&#123;</span><br><span class="line">   <span class="keyword">byte</span> b;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight shell"><figcaption><span>script</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[HEADER:  8 bytes]  8</span><br><span class="line">[a:       1 byte ]  9</span><br><span class="line">[padding: 3 bytes] 12</span><br><span class="line">[b:       1 byte ] 13</span><br><span class="line">[padding: 3 bytes] 16</span><br></pre></td></tr></table></figure>
<p>a后面的3个字节就是为了使其4字节对齐。这3个字节只能浪费不能给B使用。</p>
<p>最后一个规则可以用于节约一些内存空间：当子类的第一个属性是long或者double类型且父类没有以8字节边界结束。</p>
<blockquote>
<p>规则五：子类的第一个字段是doubel或long且父类没有以8字节边界结束，JVM打破2的规则，先存储int、short、byte、reference来填补空缺。</p>
</blockquote>
<p>例如：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">A</span> </span>&#123;</span><br><span class="line">  <span class="keyword">byte</span> a;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">B</span> </span>&#123;</span><br><span class="line">  <span class="keyword">long</span> b;</span><br><span class="line">  <span class="keyword">short</span> c;  </span><br><span class="line">  <span class="keyword">byte</span> d;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>内存布局如下：</p>
<figure class="highlight shell"><figcaption><span>script</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">[HEADER:  8 bytes]  8</span><br><span class="line">[a:       1 byte ]  9</span><br><span class="line">[padding: 3 bytes] 12</span><br><span class="line">[c:       2 bytes] 14</span><br><span class="line">[d:       1 byte ] 15</span><br><span class="line">[padding: 1 byte ] 16</span><br><span class="line">[b:       8 bytes] 24</span><br></pre></td></tr></table></figure>

<p>在字节12的位置，A类结束了。JVM打破2的规则放入short和byte类型，节约了4字节中的3个字节，否则将浪费掉。</p>
<h5 id="3-4-数组的内存布局"><a href="#3-4-数组的内存布局" class="headerlink" title="3.4 数组的内存布局"></a>3.4 数组的内存布局</h5><p>数组类型有一个额外的头部字段保存数组的长度，接下来是数组的元素，数组作为普通对象也是8字节对齐的。</p>
<p>这是byte[3]的布局：</p>
<figure class="highlight shell"><figcaption><span>script</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[HEADER:  12 bytes] 12</span><br><span class="line">[[0]:      1 byte ] 13</span><br><span class="line">[[1]:      1 byte ] 14</span><br><span class="line">[[2]:      1 byte ] 15</span><br><span class="line">[padding:  1 byte ] 16</span><br></pre></td></tr></table></figure>

<p>这是long[3]的布局:</p>
<figure class="highlight shell"><figcaption><span>script</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[HEADER:  12 bytes] 12</span><br><span class="line">[padding:  4 bytes] 16</span><br><span class="line">[[0]:      8 bytes] 24</span><br><span class="line">[[1]:      8 bytes] 32</span><br><span class="line">[[2]:      8 bytes] 40</span><br></pre></td></tr></table></figure>

<h5 id="3-5-内部类的内存布局"><a href="#3-5-内部类的内存布局" class="headerlink" title="3.5 内部类的内存布局"></a>3.5 内部类的内存布局</h5><p>非静态内部类有一个额外的隐藏字段，持有外部类的引用。这个字段是一个常规的引用,它符合对象在内存布局的规则。内部类因此有4字节额外的开销。</p>

    </div>

    
    
    
        <div class="reward-container">
  <div>赏你一杯咖啡</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.png" alt="wangduwei 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.jpeg" alt="wangduwei 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>wangduwei
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://wangduwei.top/java-object-layout.html" title="对象的内存布局">https://wangduwei.top/java-object-layout.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JVM/" rel="tag"># JVM</a>
          </div>

        
  <div class="post-widgets">
    <div class="wp_rating">
      <div id="wpac-rating"></div>
    </div>
  </div>


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/java-multithreading-synchronized.html" rel="prev" title="Java synchronized">
      <i class="fa fa-chevron-left"></i> Java synchronized
    </a></div>
      <div class="post-nav-item">
    <a href="/cpu-cache-overview.html" rel="next" title="CPU的缓存">
      CPU的缓存 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
      <div class="tabs tabs-comment">
        <ul class="nav-tabs">
            <li class="tab"><a href="#comment-gitalk">gitalk</a></li>
            <li class="tab"><a href="#comment-valine">valine</a></li>
        </ul>
        <div class="tab-content">
            <div class="tab-pane gitalk" id="comment-gitalk">
              <div class="comments" id="gitalk-container"></div>
            </div>
            <div class="tab-pane valine" id="comment-valine">
              <div class="comments" id="valine-comments"></div>
            </div>
        </div>
      </div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E6%A6%82%E8%BF%B0"><span class="nav-number">1.</span> <span class="nav-text">一、概述</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%AF%B9%E8%B1%A1%E5%A4%B4%EF%BC%88object-header%EF%BC%89"><span class="nav-number">2.</span> <span class="nav-text">二、对象头（object header）</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#2-1-mark-word%EF%BC%9A"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 mark word：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-class-word"><span class="nav-number">2.2.</span> <span class="nav-text">2.2 class word:</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-3-%E6%95%B0%E7%BB%84%E9%95%BF%E5%BA%A6%EF%BC%9A"><span class="nav-number">2.3.</span> <span class="nav-text">2.3 数组长度：</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E5%AE%9E%E4%BE%8B%E6%95%B0%E6%8D%AE%E5%92%8C%E5%AF%B9%E9%BD%90%E5%A1%AB%E5%85%85"><span class="nav-number">3.</span> <span class="nav-text">三、实例数据和对齐填充</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-1-%E6%B2%A1%E6%9C%89%E5%B1%9E%E6%80%A7%E7%9A%84%E7%B1%BB%E7%9A%84%E5%86%85%E5%AD%98%E5%B8%83%E5%B1%80"><span class="nav-number">3.1.</span> <span class="nav-text">3.1 没有属性的类的内存布局</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-2-Object%E5%AD%90%E7%B1%BB%E7%9A%84%E5%86%85%E5%AD%98%E5%B8%83%E5%B1%80"><span class="nav-number">3.2.</span> <span class="nav-text">3.2 Object子类的内存布局</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-3-%E5%AD%90%E7%B1%BB%E7%9A%84%E5%86%85%E5%AD%98%E5%B8%83%E5%B1%80"><span class="nav-number">3.3.</span> <span class="nav-text">3.3 子类的内存布局</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-4-%E6%95%B0%E7%BB%84%E7%9A%84%E5%86%85%E5%AD%98%E5%B8%83%E5%B1%80"><span class="nav-number">3.4.</span> <span class="nav-text">3.4 数组的内存布局</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-5-%E5%86%85%E9%83%A8%E7%B1%BB%E7%9A%84%E5%86%85%E5%AD%98%E5%B8%83%E5%B1%80"><span class="nav-number">3.5.</span> <span class="nav-text">3.5 内部类的内存布局</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="wangduwei"
      src="/images/avatar.jpeg">
  <p class="site-author-name" itemprop="name">wangduwei</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/duweiwang" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;duweiwang" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:wangduwei8@gmail.com" title="E-Mail → mailto:wangduwei8@gmail.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">wangduwei</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">53k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">48 分钟</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/medium-zoom@1/dist/medium-zoom.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>



  <script>
  if (CONFIG.page.isPost) {
    wpac_init = window.wpac_init || [];
    wpac_init.push({
      widget: 'Rating',
      id    : 31838,
      el    : 'wpac-rating',
      color : 'fc6423'
    });
    (function() {
      if ('WIDGETPACK_LOADED' in window) return;
      WIDGETPACK_LOADED = true;
      var mc = document.createElement('script');
      mc.type = 'text/javascript';
      mc.async = true;
      mc.src = '//embed.widgetpack.com/widget.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);
    })();
  }
  </script>












  

  

<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.css">

<script>
NexT.utils.loadComments(document.querySelector('#gitalk-container'), () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js', () => {
    var gitalk = new Gitalk({
      clientID    : '16c7d02bc3ca2bae3d85',
      clientSecret: 'bfda6fb671841e71f55e41fdd3fb794c8dbf40b2',
      repo        : 'duweiwang.github.io',
      owner       : 'duweiwang',
      admin       : ['duweiwang'],
      id          : '5ec224136b849ae5347dd5569edbc848',
        language: '',
      distractionFreeMode: true
    });
    gitalk.render('gitalk-container');
  }, window.Gitalk);
});
</script>


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : '45lTcsdp8QJNGsmN5wEaOtV5-gzGzoHsz',
      appKey     : 'QsK8vR7pb8w0M1eIk7QE50yF',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>


  <!-- 页面点击小红心 -->
  
        <script type="text/javascript" src="/js/love.js"></script>
  
</body>
</html>
